<template>
  <div class="user-management-container">
    <el-card style="max-width: 100%">
      <!-- 标题 -->
      <div class="header">
        <h2>
          <el-icon>
            <UserFilled />
          </el-icon>用户管理
        </h2>
        <el-button style="
            width: 115px;
            height: 30px;
            font-size: 16px;
            border-radius: 5px;
          " type="primary" size="small" @click="drawer = true">
          <el-icon>
            <Plus />
          </el-icon>
          新增用户
        </el-button>
      </div>

      <hr />

      <!-- 搜索区域 -->
      <div class="search-bar" style="margin-top: 10px">
        <el-form :inline="true" :model="searchForm" label-width="60px">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.user_name" placeholder="请输入用户名" style="width: 310px" />
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="searchForm.role_id" placeholder="全部" style="width: 180px">
              <el-option label="全部" value="" />
              <el-option label="系统管理员" value="1" />
              <el-option label="食堂经理" value="2" />
              <el-option label="采购员" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="全部" style="width: 180px">
              <el-option label="删除" value="-1" />
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetSearch" style="
                width: 85px;
                height: 30px;
                font-size: 15px;
                border-radius: 5px;
              "><el-icon>
                <RefreshRight />
              </el-icon>重置</el-button>
            <el-button type="primary" @click="handleSearch" style="
                width: 85px;
                height: 30px;
                font-size: 15px;
                border-radius: 5px;
              "><el-icon>
                <Search />
              </el-icon>查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格 -->
      <div class="table-container">
        <el-table :data="users" v-loading="loading" :border="true" style="width: 100%">
          <el-table-column label="序号" width="100" align="center">
            <template #default="{ row }">
              {{ row.user_id }}
            </template>
          </el-table-column>
          <el-table-column prop="user_name" label="用户名" width="150" />
          <el-table-column prop="user_name" label="姓名" width="150" />
          <!-- 角色：数字 → 中文 -->
          <el-table-column label="角色" width="140">
            <template #default="{ row }">
              {{
                { 1: "系统管理员", 2: "食堂经理", 3: "采购员" }[row.role_id] ||
                "-"
              }}
            </template>
          </el-table-column>
          <el-table-column label="联系电话" width="140">
            <template #default="{ row }">
              {{ row.phone || "-" }}
            </template>
          </el-table-column>
          <el-table-column label="邮箱" width="240">
            <template #default="{ row }">
              {{ row.email || "-" }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="row.status === 1
                ? 'success'
                : row.status === 0
                  ? 'warning'
                  : 'danger'
                " size="small">
                {{
                  row.status === 1 ? "启用" : row.status === 0 ? "禁用" : "删除"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="最后登录时间" width="220">
            <template #default="{ row }">
              {{
                row.created_at
                  ? row.created_at.slice(0, 16).replace("T", " ")
                  : "-"
              }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="handleEdit(row)">
                <el-icon>
                  <Edit />
                </el-icon>
                编辑
              </el-button>
              <el-button size="small" type="primary" :loading="resetLoading" @click="submitResetPassword(row)">
                <el-icon>
                  <Key />
                </el-icon>
                重置密码
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)" :disabled="row.status === -1">
                <el-icon>
                  <Delete />
                </el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          :page-sizes="[10, 20, 30, 40]" layout="prev, pager, next, sizes, jumper, ->, total" background
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>

  <!-- 新增用户抽屉-->
  <el-drawer v-model="drawer" :show-close="true" direction="rtl" size="650px">
    <div class="drawer-header" style="margin: 0; padding: 15px; margin-bottom: 0px">
      <h4 style="margin: 0; font-size: 20px;position: absolute;top: 16px;">新增用户</h4>
    </div>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="user-form"
      style="position: relative;bottom: 50px;right: 10px;">
      <!-- 表单项 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="姓名" prop="realName">
        <el-input v-model="editForm.realName" placeholder="请输入姓名" />
      </el-form-item>

      <el-form-item label="角色" prop="role_id">
        <el-select v-model="form.role_id" placeholder="请选择" style="width: 100%">
          <el-option label="系统管理员" value="1" />
          <el-option label="食堂经理" value="2" />
          <el-option label="采购员" value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择" style="width: 100%">
          <el-option label="禁用" value="0" />
          <el-option label="启用" value="1" />
          <el-option label="删除" value="-1" />
        </el-select>
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="备注" prop="notes">
        <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
    <!-- 底部按钮 -->
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="submit">保存</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 编辑抽屉 -->
  <el-drawer v-model="editDrawer" :show-close="true" direction="rtl" size="650px" :before-close="handleEditClose">
    <div class="drawer-header" style="margin: 0; padding: 15px; margin-bottom: 0px">
      <h4 style="margin: 0; font-size: 20px;position: absolute;top: 16px;">编辑用户</h4>
    </div>
    <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px"
      style="position: relative; bottom: 50px;right: 10px;">
      <!-- 表单项 -->
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="用户名" prop="user_name">
          <el-input v-model="editForm.user_name" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="姓名" prop="user_name">
          <el-input v-model="editForm.user_name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择" style="width: 100%">
            <el-option label="系统管理员" value="1" />
            <el-option label="食堂经理" value="2" />
            <el-option label="采购员" value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择" style="width: 100%">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
            <el-option label="删除" value="-1" />
          </el-select>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
    </el-form>
    <template #footer>
      <div style="text-align: right">
        <el-button @click="editDrawer = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="submitEdit">保存</el-button>
      </div>
    </template>
  </el-drawer>


</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getUserInfo,
  addUser,
  updateUser,
  resetUserPassword,
} from "../../api/user.js";
import { Plus, Search, RefreshRight } from "@element-plus/icons-vue";

/* ----------------  添加相关 ---------------- */
const drawer = ref(false); // 新增抽屉
const formRef = ref(null); // 新增表单 ref
const saveLoading = ref(false); // 新增保存 loading
const form = reactive({
  // 新增表单数据
  username: "",
  realName: "",
  role: "",
  phone: "",
  email: "",
  status: "1",
  remark: "",
});

// 新增校验规则
const rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  // realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  role_id: [{ required: true, message: "请选择角色", trigger: "change" }],
};
/* 新增提交 */
async function submit() {
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;
  saveLoading.value = true;
  try {
    // 添加调试日志，查看请求参数
    console.log("提交的用户数据:", {
      user_name: form.username,
      role_id: form.role_id,
      phone: form.phone,
      email: form.email,
      notes: form.remark,
      status: Number(form.status),
    });

    await addUser({
      user_name: form.username,
      role_id: form.role_id,
      phone: form.phone,
      email: form.email,
      notes: form.remark,
      status: Number(form.status),
    });
    ElMessage.success("用户添加成功");
    drawer.value = false;
    fetchData();
  } catch (e) {
    console.error("添加用户错误:", e);
    ElMessage.error(e?.message || "添加用户失败");
  } finally {
    saveLoading.value = false;
  }
}

/* ----------------  编辑相关 ---------------- */
const editDrawer = ref(false);
const editFormRef = ref(null);
const editLoading = ref(false);
const originalData = ref({});
const editForm = reactive({
  user_id: "",
  user_name: "",
  realName: "",
  role: "",
  status: "1",
  phone: "",
  email: "",
  remark: "",
});

// 编辑校验规则
const editRules = {
  user_name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  role: [{ required: true, message: "请选择角色", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};
/* 打开编辑抽屉 */
function handleEdit(row) {
  Object.assign(editForm, {
    user_id: row.user_id || "",
    user_name: row.user_name || "",
    realName: row.realName || "",
    phone: row.phone || "",
    email: row.email || "",
    remark: row.notes || "",
    role:
      row.role_id === 1
        ? "系统管理员"
        : row.role_id === 2
          ? "食堂经理"
          : "采购员",
    status: String(row.status || 0),
  });
  originalData.value = { ...editForm };

  editDrawer.value = true;
}
/* 编辑提交 */
async function submitEdit() {
  const valid = await editFormRef.value.validate().catch(() => false);
  if (!valid) return;
  editLoading.value = true;
  try {
    const payload = {
      user_name: editForm.user_name,
      role_id:
        editForm.role === "系统管理员"
          ? 1
          : editForm.role === "食堂经理"
            ? 2
            : 3,
      phone: editForm.phone,
      email: editForm.email,
      notes: editForm.remark,
      status: Number(editForm.status),
    };
    await updateUser(editForm.user_id, payload);
    ElMessage.success("用户修改成功");
    editDrawer.value = false;
    fetchData();
  } catch (e) {
    ElMessage.error(e?.message || "修改用户失败");
  } finally {
    editLoading.value = false;
  }
}

/* ----------------  搜索 & 表格 & 分页 ---------------- */
const searchForm = reactive({ username: "", role: "", status: "" });
const users = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

async function fetchData() {
  loading.value = true;
  try {
    const res = await getUserInfo({
      ...searchForm,
      page: currentPage.value,
      pageSize: pageSize.value,
    });
    users.value = res.list || res.data || [];
    total.value = res.total || 0;
  } catch (e) {
    ElMessage.error(e?.message || "加载失败");
  } finally {
    loading.value = false;
  }
}

/* ----------------  重置密码 ---------------- */
// 一键重置密码
const resetLoading = ref(false);
const DEFAULT_PASSWORD = "123456aA"; // 固定密码

async function submitResetPassword(row) {
  ElMessageBox.confirm(
    `确定要将用户 "${row.user_name}" 的密码重置为 "${DEFAULT_PASSWORD}" 吗？`,
    "重置密码确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      resetLoading.value = true;
      try {
        await resetUserPassword(row.user_id, DEFAULT_PASSWORD);
        ElMessage.success(
          `用户 "${row.user_name}" 密码已重置为：${DEFAULT_PASSWORD}`
        );
      } catch (e) {
        ElMessage.error(e?.message || "重置失败");
      } finally {
        resetLoading.value = false;
      }
    })
    .catch(() => {
      // 用户取消操作
      ElMessage.info("已取消重置密码");
    });
}

/* ----------------  删除相关 ---------------- */
// 删除用户
function handleDelete(row) {
  ElMessageBox.confirm(
    `确定要${row.status === -1 ? "已删除" : "删除"}用户 "${row.user_name
    }" 吗？`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        // 使用 updateUser 接口将用户状态设置为 -1 (删除状态)
        await updateUser(row.user_id, { status: -1 });
        ElMessage.success("用户删除成功");
        fetchData(); // 重新加载数据
      } catch (e) {
        ElMessage.error(e?.message || "删除失败");
      }
    })
    .catch(() => {
      // 用户取消删除
    });
}

/* ---------------- 工具函数 ---------------- */
function handleSearch() {
  currentPage.value = 1;
  fetchData();
}
function resetSearch() {
  console.log("重置前的搜索条件:", searchForm);

  Object.assign(searchForm, {
    user_name: "",
    role_id: "",
    status: "",
  });

  console.log("重置后的搜索条件:", searchForm);

  handleSearch();
}

function handleSizeChange(val) {
  pageSize.value = val;
  fetchData();
}
function handleCurrentChange(val) {
  currentPage.value = val;
  fetchData();
}

// 关闭添加抽屉前提示
function handleClose(done) {
  ElMessageBox.confirm("确定要放弃填写吗？", "提示", { type: "warning" })
    .then(() => done())
    .catch(() => { });
}

// 关闭编辑抽屉前提示
function handleEditClose(done) {
  // 比较当前表单和原始数据是否一致
  const hasChanged = Object.keys(editForm).some(key => {
    return editForm[key] !== originalData.value[key];
  });

  if (hasChanged) {
    ElMessageBox.confirm("确定要放弃修改吗？", "提示", { type: "warning" })
      .then(() => done())
      .catch(() => { });
  } else {
    // 没有修改，直接关闭
    done();
  }
}

onMounted(fetchData);
</script>

<style scoped lang="less">
:deep(.custom-drawer .el-drawer__header) {
  margin-bottom: 0px !important;
}

// /* 2. 表单区域内边距：保证整体布局紧凑 */
// ::v-deep .user-form {
//     padding: 15px;
// }

// /* 3. 表单项垂直间距：统一各输入项的上下距离 */
// ::v-deep .el-form-item {
//     margin-bottom: 20px !important;
// }

.user-management-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0px;
  border-bottom: 1px solid #ebeef5;

  h2 {
    font-size: 18px;
    color: #303133;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .el-button {
    padding: 8px 16px;
    font-size: 14px;
    border-radius: 4px;
  }

  .el-drawer__header {
    height: 30px;
    margin-bottom: 0px;
  }
}

.search-bar {
  background: white;
  padding: 10px;
  border-radius: 8px;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  text-align: right;
  margin-top: 20px;
  padding-right: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-form {
  margin-bottom: 5px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-form-item__label {
  font-weight: normal;
  color: #303133;
}
</style>
